<template>
  <div class="box">
    <header>
      <span class='iconfont ico' @click="() => { this.$router.go(-1) }">&#xe65a;</span>
      <h4>调控设置</h4>
    </header>
    <div class="conent">
      <div class="automatic">
        <span v-if="checked"> 自动</span><span v-else> 手动</span><van-switch v-model="checked" class="switche" @change="onchange" active-color="#666" />
      </div>
      <div class="conent_box">
        <p class="red_box"></p>
        <div>
          <div class="day">
            <p>一号温棚</p>
            <p>2020/4/20</p>
          </div>
          <div class="text">
            <h2>温度过高</h2>
            <p>温度过高会导致农产品坏死</p>
          </div>
          <div class="automatic">
          </div>
          <div class="manual" v-if="!checked">
            <van-button type="danger" @click="call('a')">报警</van-button>&nbsp;
            <van-button type="info" @click="cancel('b')">取消</van-button>
          </div>
          <!-- <span @click="() => { this.$router.push('/setup') }">去设置</span> -->
        </div>
      </div>
      <div class="conent_box">
        <p class="red_box"></p>
        <div>
          <div class="day">
            <p>一号温棚</p>
            <p>2020/4/20</p>
          </div>
          <div class="text">
            <h2>湿度过高</h2>
            <p>湿度过高会导致农产品坏死</p>
          </div>
          <div class="manual" v-if="!checked">
            <van-button type="danger" @click="call('c')">报警</van-button>&nbsp;
            <van-button type="info" @click="cancel('d')">取消</van-button>
          </div>
          <!-- <span @click="() => { this.$router.push('/setup') }">去设置</span> -->
        </div>
      </div>
      <div class="conent_box">
        <p class="red_box"></p>
        <div>
          <div class="day">
            <p>一号温棚</p>
            <p>2020/4/20</p>
          </div>
          <div class="text">
            <h2>光照过高</h2>
            <p>光照过高会导致农产品坏死</p>
          </div>
          <div class="automatic">
          </div>
          <div class="manual" v-if="!checked">
            <van-button type="danger" @click="call('e')">报警</van-button>&nbsp;
            <van-button type="info" @click="cancel('f')">取消</van-button>
          </div>
          <!-- <span @click="() => { this.$router.push('/setup') }">去设置</span> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Switch, Toast, Button } from 'vant'

Vue.use(Switch)
Vue.use(Button)

export default {
  data() {
    return {
      checked: true,
       mqtt: '',
       data: {}
    }
  },
  mounted () {
    var reconnectTimeout = 3000;	//连接超时时长
    var host = '49.232.150.163';    // hostname or IP address//MQTT服务器ip地址
    var port = 9001;					//MQTT代理器端口
    var topic = 'Temp';        // 定义订阅主题类型温度
    var topic1 = 'Hum';				// 定义订阅主题类型湿度
    var clientId = 'client-' + Math.ceil(Math.random() * 1000);
    var topic2 = 'Hv';				// 定义订阅主题类型光照强度
    var topic3 = 'Co2';						// 定义订阅主题类型CO2浓度
    var useTLS = false;
    var username = null;
    var password = null;
    //username = "test";
    //password = "123456";
    var cleansession = true;
    var addr = [];
    const MQTTconnect = () => {     
      //连接函数：连接到MQTT代理器
      this.mqtt = new Paho.MQTT.Client(host, port, clientId);
      var options = {
        invocationContext: {
          host: host,
          port: port,
          path: this.mqtt.path,
          clientId: clientId
        },
        timeout: 5,
        useSSL: useTLS,
        cleanSession: cleansession,
        onSuccess: onConnect,
        onFailure: function (message) {
          alert("connect failed..............");//调试语句连接代理器 失败打印
          // $('#status').val("Connection failed: " + message.errorMessage + "Retrying");
          setTimeout(MQTTconnect, reconnectTimeout);
        }
      };

      this.mqtt.onConnectionLost = onConnectionLost;
      this.mqtt.onMessageArrived = onMessageArrived;

      if (username != null) {
        options.userName = username;
        options.password = password;
      }
      this.mqtt.connect(options);
    }

    const onConnect = () =>  {		//连接代理器成功回调函数			
      // Connection succeeded; subscribe to our topic//作为客户端向代理器订阅相关主题
      this.mqtt.subscribe(topic, { qos: 0 });//订阅topic（'Temp'）即温度主题，
    }

    function onConnectionLost(response) {
      setTimeout(MQTTconnect, reconnectTimeout);
      // $('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");

    }

    var onMessageArrived = (message) => {//收到所订阅类型消息回调函数，即只要有人发布自己所订阅的消息类型就会调用此函数
      var topic = message.destinationName;//message.destinationName为消息类型，自己定义变量去接收并且解析
      var payload = message.payloadString;//message.payloadString为消息数据，

      var stra = String(payload)
      
    };
    MQTTconnect()

    axios({
      url: '/api/IntelligentAgriculture/receiveDataController/checkToken',
      method: 'get',
      headers: {'token': localStorage.getItem('token')}
    }).then(res => {
      if (res.data.code === 1001) {
        this.$router.push('/login')
      }
    })
  },
  methods: {
    call (val) {
      const vals = val
      const tps = 'server_control'
      var message = new Paho.MQTT.Message(vals);
      message.destinationName = tps;
      message.qos = 0;
      this.mqtt.send(message);
      Toast('报警成功')
      this.mqtt.publish(tps, 0, vals);
    },
    cancel (val) {
      const vals = val
      const tps = 'server_control'
      var message = new Paho.MQTT.Message(vals);
      message.destinationName = tps;
      message.qos = 0;
      this.mqtt.send(message);
      Toast('取消成功')
      this.mqtt.publish(tps, 0, vals);
    },
    onchange (value) {
      if (value) {
        const vals = 'aa'
        const tps = 'server_control'
        var message = new Paho.MQTT.Message(vals);
        message.destinationName = tps;
        message.qos = 0;
        this.mqtt.send(message);
        Toast('已切换为自动')
        this.mqtt.publish(tps, 0, vals);
        
      } else {
        const vals = 'bb'
        const tps = 'server_control'
        var message = new Paho.MQTT.Message(vals);
        message.destinationName = tps;
        message.qos = 0;
        this.mqtt.send(message);
        Toast('已切换为手动')
        this.mqtt.publish(tps, 0, vals);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .box {
    height: 100%;
    padding: 0 40px;
    display: flex;
    flex-direction: column;
    header {
      position: relative;
      padding: 30px 0;
      span {
      position: absolute;
      }
      h4 {
        text-align: center;
        font-size: 34px;
      }
    }
    .conent {
      .automatic {
        padding: 0 0 20px 0;
        overflow: hidden;
        .van-switch {
          float: right;
          height: 40px;
          /deep/ .van-switch__node {
            height: 40px;
          }
        }
        span {
          float: right;
        }
      }
      .conent_box {
        overflow: hidden;
        border-radius: 20px;
        padding: 0 20px 30px 50px;
        background: #ffffff;
        position: relative;
        margin-bottom: 40px;
        &:nth-of-type(4) {
          margin-bottom: 0;
        }
        .day {
          font-size: 24px;
          display: flex;
          justify-content: space-between;
          padding: 40px 0 30px 0;
          p {
            &:nth-of-type(2) {
              color: #b4b4b4;
            }
          }
        }
        .text {
          font-size: 24px;
          float: left;
          h2 {
            font-size: 40px;
            padding-bottom: 15px;
          }
          p {
            color: #b4b4b4;
          }
        }
        .automatic {
          float: right;
          display: block;
        }
        .red_box {
          width: 80px;
          background: red;
          height: 10px;
          border-radius: 5px;
        }
        .manual {
          overflow: hidden;
          width: 100%;
          padding: 20px 0 0 0;
        }
      }
    }
  }
</style>
